from odoo import fields, models, api
from odoo.exceptions import UserError


from odoo.addons.rp_courier_management.models.setting.rp_value_added_service import VALUE_TYPE, VALUE_CATEGORY


class RPAvailableShipperValueAddedTran(models.TransientModel):
    _name = 'rp.available.shipper.value.added.tran'
    _description = '可用增值服务'
    _rec_name = 'rp_asva_code'

    def _default_auto_rp_asva_code(self):
        records = self.env['rp.available.shipper.value.added.tran'].search([])
        return "RP_ASVA" + str(len(records) + 1).zfill(3)

    rp_asva_code = fields.Char(string='索引码', default=_default_auto_rp_asva_code, index=True, copy=False, readonly=True)
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)

    value_added_id = fields.Many2one(string='可用增值服务', comodel_name='rp.value.added.service')
    value_added_type = fields.Selection(string='类型', selection=VALUE_TYPE)
    value_added_category = fields.Selection(string='大类', selection=VALUE_CATEGORY)
    tag_price = fields.Float(string='标价', digits=(8, 3), default=0)
    sale_adjusted_price = fields.Float(string='调后价', digits=(8, 3), default=0)

    used_sale_price_adjust_ids = fields.Many2many(string='使用调价', comodel_name='rp.shipper.sale.price.adjustment', readonly=True,
                                                  relation='rp_asva_and_price_adjustment_rel', column1='asva_id', column2='price_adjustment_id')

    def action_rewrite_sva(self):
        records = self.browse(self.env.context.get('active_ids'))
        ship_order = self.env['rp.ship.order'].browse(self.env.context.get('ship_order_id'))
        used_value_added_rcds = ship_order.rp_ship_order_value_added_line_ids.mapped('value_added_id')

        value_added_list = []
        for r in records:
            # 1、查询使用过的增值服务
            if r.value_added_id.id not in used_value_added_rcds.ids:
                # 2、创建增值服务明细
                value_added_values = {'rp_ship_order_id': ship_order.id,
                                      'value_added_id': r.value_added_id.id,
                                      'value_added_type': r.value_added_type,
                                      'value_added_category':r.value_added_category,
                                      'tag_price': r.tag_price,
                                      'sale_adjusted_price': r.sale_adjusted_price,
                                      'used_sale_price_adjust_ids': [(6, 0, r.used_sale_price_adjust_ids.ids)], }
                value_added_list.append((0, 0, value_added_values))
        # 2、销售订单填充数据
        ship_order.write({'rp_ship_order_value_added_line_ids': value_added_list})
